package com.societyGames.flashForms
{
import flash.display.DisplayObject;
import flash.display.Sprite;

//Scale only if we start to run out of room.
public class HeadersContainer extends Sprite //implements IChangeSize
{
  private var _headers:Array = []; //DisplayObject
  private var _desiredHeight:Number;
  private var _desiredWidth:Number;

  private var _selectedHeader:DisplayObject;

  public override function set height(value:Number):void
  {
    if (value != this._desiredHeight)
    {
      this._desiredHeight = value;
      recalculateHeight();
    }
  }

  public override function set width(value:Number):void
  {
    if (value != this._desiredWidth)
    {
      this._desiredWidth = value;
      recalculateWidth();
    }
  }

  public function addHeader(header:DisplayObject):void
  {
    //Add item to main list
    this._headers.push(header);

    //Add to render list
    this.addChildAt(header, 0);

    recalculate();
  }

  //Selects the header regardless of whether it's different or not.
  private function doSelectHeader(header:DisplayObject):void
  {
    this._selectedHeader = header;
  }

  //Only selects header if different.
  public function selectHeader(header:DisplayObject):void
  {
    if (this._selectedHeader != header)
    {
      doSelectHeader(header);
    }
  }

  public function removeHeader(header:DisplayObject):void
  {
    //See if the tab is present.
    var index:int = this._headers.indexOf(header);
    if (index != -1)
    {
      //remove from main list.
      this._headers.splice(index, 1);

      //Stop rendering
      this.removeChild(header);

      //Rearrange everything
      recalculate();
    }
  }

  private function recalculate():void
  {
    recalculateHeight();
    recalculateWidth();
  }

  private function recalculateWidth():void
  {
    var headerWidth:Number = this._desiredWidth / this._headers.length;
    var nextHeaderX:Number = 0;
    for each (var header:DisplayObject in this._headers)
    {
      header.x = nextHeaderX;
      header.width = headerWidth;
      nextHeaderX += headerWidth;
    }
  }

  private function recalculateHeight():void
  {
    for each (var header:DisplayObject in this._headers)
    {
      header.y = 0;
      header.height = this._desiredHeight;
    }
  }
}
}